package com.csvw.skr.console.resource;

import com.csvw.skr.basic.core.JobType;
import com.csvw.skr.basic.entity.User;
import com.csvw.skr.console.service.OrganizationService;
import com.csvw.skr.console.service.UserService;

import com.webonn.frame.core.Pagination;
import com.webonn.frame.util.APIResultBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.validation.constraints.NotNull;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/9/19.
 */
@PermitAll
@Produces({MediaType.APPLICATION_JSON + "; charset=UTF-8", MediaType.TEXT_HTML + "; charset=UTF-8"})
@RestController
@RequestMapping(value="/console")
public class UserResource {
    @Autowired
    private UserService userService;
    @Autowired
    private OrganizationService organizationService;

    /************************************************************************************************
     * user management
     */

    @RequestMapping(value="/user", method= RequestMethod.GET)
    public Response queryUsers(@DefaultValue("0") @QueryParam("start") int start,
                               @DefaultValue("20") @QueryParam("limit") int limit,
                               @Context UriInfo uriInfo) {
        MultivaluedMap<String, String> filterSearch = uriInfo.getQueryParameters();
        Pagination result = userService.queryUsers(start, limit, filterSearch);
        return APIResultBuilder.OK(result);
    }

    @RolesAllowed({JobType.ADMINISTRATOR})
    @RequestMapping(value="/user", method= RequestMethod.POST)
    public Response addUser(@NotNull User user) {
        return APIResultBuilder.CREATED(userService.addUser(user));
    }

    @RolesAllowed({JobType.ADMINISTRATOR})
    @RequestMapping(value="/user/{id}", method= RequestMethod.PUT)
    public Response updateUser(@NotNull @PathVariable String userId, @NotNull User user) {
        return APIResultBuilder.CREATED(userService.updateUser(user));
    }

    @RequestMapping(value="/user/{id}", method= RequestMethod.GET)
    public Response getUser(@NotNull @PathVariable String id) {
        Map<String, Object> result = userService.getUserByUserName(id);
        if (result != null) {
            result.put("organizationName", organizationService.getOrganizationInfo((String) result.get("organization")));
            return APIResultBuilder.OK(result);
        } else {
            return APIResultBuilder.NOT_FOUND("未找到用户信息");
        }
    }

    @RolesAllowed({JobType.ADMINISTRATOR})
    @RequestMapping(value="/user/{id}", method= RequestMethod.DELETE)
    public Response deleteUser(@NotNull @PathVariable String id) {
        return APIResultBuilder.NO_CONTENT(userService.deleteUser(id));
    }

    /**
     * 添加用户角色
     */
    @RolesAllowed({JobType.ADMINISTRATOR})
    @RequestMapping(value="/user/role/{userId}", method= RequestMethod.POST)
    public Response addUserRole(@PathVariable String userId, List<String> roleIds) {
        return APIResultBuilder.CREATED(userService.addUserRole(userId, roleIds));
    }

    /**
     * 查询用户角色
     */
    @RequestMapping(value="/user/role/{userId}", method= RequestMethod.GET)
    public Response queryUserRole(@PathVariable String userId) {
        return APIResultBuilder.OK(userService.queryUserRole(userId));
    }

    /**
     * 用户是否存在
     */
    @RequestMapping(value="/user/exist/{type}/{value}", method= RequestMethod.GET)
    public Response getUserExist(@NotNull @PathVariable String type, @NotNull @PathVariable String value) {
        boolean result;
        switch (type) {
            case "id":
                result = userService.getUser(value) == null;
                break;
            case "phone":
            case "email":
                result = userService.getExist(type, value) == null;
                break;
            default:
                result = true;
        }
        return APIResultBuilder.OK(result);
    }
}
